package com.quanyan.club.thread;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.vo.resp.RespClubActivity;
import com.quanyan.common.constants.Constants;
import com.quanyan.search.entity.vo.ActivityIndexInfo;
import com.quanyan.search.service.ActivitySearchService;
import com.quanyan.search.service.impl.ActivitySearchServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * Created by yue.yuan on 2016/11/29.
 */
public class BatchActivitySolrIndexThread implements Runnable{

    private Logger logger = LoggerFactory.getLogger(BatchActivitySolrIndexThread.class);

    public String searchCloudUrl = "10.25.132.189:2181,10.25.115.183:2181,10.45.139.35:2181";

    private boolean isUpdate;     //1 插入 2 更新

    private List<Integer> activityIds;
    private ActivitySearchService activitySearchService;
    private List<RespClubActivity> respClubActivities;

    public BatchActivitySolrIndexThread(List<Integer> activityIds,
                                        List<RespClubActivity> respClubActivities,
                                        ActivitySearchService activitySearchService,
                                        boolean isUpdate){
        this.respClubActivities = respClubActivities;
        this.activitySearchService = activitySearchService;
        this.activityIds = activityIds;
        this.isUpdate = isUpdate;
    }

    @Override
    public void run() {
        logger.warn("solr地址：" + searchCloudUrl);
        if (isUpdate){
            logger.warn("-----------------------开始删除--------------------------");
            //先删除
            long t2 = System.currentTimeMillis();
            //先删除
            APIResponse response = activitySearchService.deleteDocsByIds(activityIds);
            if (!response.isRet()){
                logger.warn("删除活动"+ activityIds +"索引失败，"+ response.getErrmsg());
            }
            logger.warn("删除活动ll索引，花费：{}, {}", JSON.toJSON(response), System.currentTimeMillis()-t2);
        }

        List<ActivityIndexInfo> indexInfoList = new ArrayList<>();
        for(RespClubActivity respClubActivity : respClubActivities){
            ActivitySearchService activitySearchService = new ActivitySearchServiceImpl(searchCloudUrl);
            ActivityIndexInfo activityIndexInfo = new ActivityIndexInfo();
            activityIndexInfo.setActivity_placeAddress(respClubActivity.getPlaceAddress());
            activityIndexInfo.setActivity_categorieId(respClubActivity.getCategoryId());
            activityIndexInfo.setActivity_categorieName("");
            if (null != respClubActivity.getPlaceDubboProvider()) {
                activityIndexInfo.setActivity_site(respClubActivity.getPlaceDubboProvider().getName());
            }
            activityIndexInfo.setActivity_cityId(respClubActivity.getCityId());
            activityIndexInfo.setActivity_districtId(respClubActivity.getDistrictId());
            activityIndexInfo.setActivity_lat(respClubActivity.getLat());
            activityIndexInfo.setActivity_lng(respClubActivity.getLng());
            activityIndexInfo.setActivity_clubName(respClubActivity.getClubName());
            List<Integer> dateParams = new ArrayList<>();
            getDateParams(dateParams, respClubActivity);
            activityIndexInfo.setActivity_dateParams(dateParams);
            activityIndexInfo.setActivity_deadlineTime(respClubActivity.getSignEndTime());
            activityIndexInfo.setActivity_startTime(respClubActivity.getStartTime());
            activityIndexInfo.setActivity_endTime(respClubActivity.getEndTime());
            activityIndexInfo.setActivity_id(respClubActivity.getActivityId() + "");
            if (null != respClubActivity.getSignUserList() && respClubActivity.getLimitNum() > 0) {
                activityIndexInfo.setActivity_isFull(respClubActivity.getSignUserList().size()
                        >= respClubActivity.getLimitNum() ? 1 : 0);
            } else {
                activityIndexInfo.setActivity_isFull(0);//未报满
            }
            activityIndexInfo.setActivity_isPrime(respClubActivity.getIsPrimeTime().intValue());
            activityIndexInfo.setActivity_name(respClubActivity.getName());
            if (null != respClubActivity.getFeeType()) {//收费类型   0 AA收费，1 会员制
                if (respClubActivity.getFeeType().equals(Constants.BYTE_ZERO)) {
                    activityIndexInfo.setActivity_price(respClubActivity.getAaFee().doubleValue());
                } else {
                    List<Double> doubles = new ArrayList<>();
                    doubles.add(respClubActivity.getFemaleMemberFee().doubleValue());
                    doubles.add(respClubActivity.getMaleMemberFee().doubleValue());
                    if(null == respClubActivity.getSignUpType() || respClubActivity.getSignUpType().equals(Constants.BYTE_ZERO))
                    {
                        doubles.add(respClubActivity.getFemaleFee().doubleValue());
                        doubles.add(respClubActivity.getMaleFee().doubleValue());
                    }
                    activityIndexInfo.setActivity_price(mathUtil(doubles));
                }
            }
            if (null != respClubActivity.getRespActivityPoster()) {
                activityIndexInfo.setActivity_url(respClubActivity.getRespActivityPoster().getUrl());
            }
            logger.warn("插入数据：" + JSONObject.toJSONString(activityIndexInfo));
            indexInfoList.add(activityIndexInfo);
        }

        long t1 = System.currentTimeMillis();
        APIResponse response = activitySearchService.insertDocs(indexInfoList);
        if (response == null || !response.isRet()) {
            logger.warn("all 添加俱乐部索引失败");
            logger.warn("返回：" + JSON.toJSON(response));
        } else {
            logger.debug("添加俱乐部all索引成功");
        }

        logger.warn("添加俱乐部all索引，花费：{}", System.currentTimeMillis() - t1);
    }

    private static List<Integer> getDateParams(List<Integer> dateParams, RespClubActivity respClubActivity) {

        Calendar c = Calendar.getInstance();
        c.setTime(respClubActivity.getStartTime());
        Integer weekRange = null;
        if(c.get(Calendar.DAY_OF_WEEK) == 1){
            weekRange = 7;
        }else{
            weekRange = c.get(Calendar.DAY_OF_WEEK) - 1;
        }
        respClubActivity.setWeekRange(weekRange.byteValue());
        dateParams.add(respClubActivity.getWeekRange() + 2);
        Calendar startdate = Calendar.getInstance(Locale.CHINA);
        startdate.setTime(respClubActivity.getStartTime());
        int sh = startdate.get(Calendar.HOUR_OF_DAY);

        Calendar enddate = Calendar.getInstance(Locale.CHINA);
        enddate.setTime(respClubActivity.getStartTime());
        int eh = enddate.get(Calendar.HOUR_OF_DAY);
        if (sh <= 22 && sh >= 17 && eh >= 17 & eh <= 22) {
            dateParams.add(2);//黄金时段
        }
        if (respClubActivity.getWeekRange() == 6 || respClubActivity.getWeekRange() == 7) {
            dateParams.add(1);//属于周末
        }
        return dateParams;
    }

    private static Double mathUtil(List<Double> doubles) {
        Double lowest = 0.00;
        for (int i = 0; i < doubles.size(); i++) {
            if (i == 0) {
                lowest = doubles.get(i);
            } else {
                if (doubles.get(i) < lowest) {
                    lowest = doubles.get(i);
                }
            }
        }
        return lowest;
    }

}
